<template>
  <div class="register-page">
    <div class="register">
      <div class="login__title">{{ $t('title') }}</div>
      <div class="login__subtitle">{{ $t('hrRegisterTitle') }}</div>
      <el-form :model="registerForm" :rules="rules" ref="refRegisterForm" size="medium" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="registerForm.username" placeholder="请输入用户名" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="registerForm.name" placeholder="请输入姓名" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="registerForm.gender" placeholder="请选择性别">
                <el-option label="男" :value="1"></el-option>
                <el-option label="女" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="密码" prop="password">
              <el-input v-model="registerForm.password" placeholder="请输入密码" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="确认密码" prop="password2">
              <el-input v-model="registerForm.password2" placeholder="请输入确认密码" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                  v-model="registerForm.birthDate" type="date" placeholder="出生日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="省/市/区">
              <el-cascader
                  v-model="provinceCityArea"
                  :options="provinceCityAreaOptions"
                  :props="{ expandTrigger: 'hover', value: 'code', label: 'name' }"
                  @change="handleChange"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="registerForm.contactPhone" placeholder="请输入联系电话" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="家庭地址" prop="address">
              <el-input v-model="registerForm.address" placeholder="请输入家庭地址" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item prop="verificationCode" label="验证码">
              <el-input v-model="registerForm.verificationCode" placeholder="请输入验证码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <canvas id="captchaCanvas" width="150" height="50" @click="drawCaptcha"></canvas>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="center-container">
              <el-button type="primary" @click="onRegister" :loading="loading">注册</el-button>
              <el-button @click="onReset">重置</el-button>
              <el-button type="primary" @click="onBack">返回登录</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="footer">
      <span>版权所有 &copy; 2024 - 2026 <a href="http://www.52ejn.com" target="_blank">源码学习网</a></span><a href="http://beian.miit.gov.cn" target="_blank">粤ICP备2024308896号-1</a>
    </div>
  </div>
</template>

<script setup lang="ts">
import {inject, onMounted, reactive, ref, toRefs} from 'vue';
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {Result} from '@/types/result'
import {useCaptcha} from '@/composables/useCaptcha'
import {useRouter} from 'vue-router'
import type { JobSeekerRegisterForm } from '@/types/req/jobSeekerRegisterForm';
import candidateApi from '@/api/candidateApi';
import areas from "@/locales/area.json";

const { generatedVerificationCode, drawCaptcha } = useCaptcha()

const refRegisterForm = ref<FormInstance | null>(null);
const registerForm = reactive<JobSeekerRegisterForm>({
  username: '',
  name: '',
  password: '',
  password2: '',
  gender: undefined,
  birthDate: '',
  contactPhone: '',
  email: '',
  province: '',
  city: '',
  area: '',
  address: '',
  verificationCode: ''
})
const provinceCityArea = ref<string[]>([])
const provinceCityAreaOptions = areas.provinces
const loading = ref<boolean>(false)
const router = useRouter()

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请确认密码', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请输入性别', trigger: 'blur' }
  ],
  birthDate: [
    { required: true, message: '请输入出生日期', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const onReset = () => {
  if (refRegisterForm.value) {
    refRegisterForm.value.resetFields()
  }
  provinceCityArea.value = []
}

const refreshCaptcha = () => {
  registerForm.verificationCode = ''
  drawCaptcha()
}

const onRegister = () => {
  if (!refRegisterForm.value) {
    return
  }
  refRegisterForm.value.validate(async (valid: boolean) => {
    if (valid) {
      if (registerForm.password !== registerForm.password2) {
        ElMessage.error('两次输入的密码不一致，请重新输入')
        registerForm.password = ''
        registerForm.password2 = ''
        refreshCaptcha()
        return
      }
      if (generatedVerificationCode.value.toLowerCase() !== registerForm.verificationCode.toLowerCase()) {
        ElMessage.error('验证码错误')
        refreshCaptcha()
        return
      }
      loading.value = true
      const resp: Result<void> = await candidateApi.save(registerForm)
      if (resp && resp.code === 1) {
        ElMessage.success('注册成功')
        await router.push({ path: '/Login', query: {type: 3} })
      } else {
        ElMessage.error('注册失败:' + (resp.msg ? resp.msg : ''))
        refreshCaptcha()
        loading.value = false
      }
    }
  })
}

const handleChange = (value: string[]) => {
  if (value && value.length > 0) {
    registerForm.province = value[0]
  }
  if (value && value.length > 1) {
    registerForm.city = value[1]
  }
  if (value && value.length > 2) {
    registerForm.area = value[2]
  }
}

const onBack = () => {
  router.push({ path: '/Login', query: {type: 3} })
}

</script>

<style lang="scss">
@use "@/assets/register.scss";
</style>
